package com.zzl.alligator.management.system.controller;

import com.zzl.alligator.common.constant.Constants;
import com.zzl.alligator.common.constant.SystemConstants;
import com.zzl.alligator.common.enums.BusinessTypeEnum;
import com.zzl.alligator.common.util.ServletUtils;
import com.zzl.alligator.common.util.StringUtils;
import com.zzl.alligator.framework.aspectj.annotation.Log;
import com.zzl.alligator.framework.base.controller.BaseController;
import com.zzl.alligator.framework.security.LoginUser;
import com.zzl.alligator.framework.security.service.TokenService;
import com.zzl.alligator.framework.support.web.vo.JsonResult;
import com.zzl.alligator.management.system.domain.SysMenu;
import com.zzl.alligator.management.system.service.impl.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 菜单控制器
 *
 * @author zhouziliang
 * @since 2020/7/3
 */
@RestController
@RequestMapping("/system/menu")
public class SysMenuController extends BaseController {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysMenuService menuService;


    /**
     * 获取菜单列表
     *
     * @param menu
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:menu:list')")
    @GetMapping
    public JsonResult menuList(SysMenu menu) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long userId = loginUser.getUser().getUserId();
        List<SysMenu> menuList = menuService.findMenuList(menu, userId);
        return JsonResult.success(menuList);
    }

    /**
     * 根据菜单编号获取菜单详细信息
     *
     * @param menuId
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:menu:query')")
    @GetMapping("/{menuId}")
    public JsonResult menuDetail(@PathVariable Long menuId) {
        return JsonResult.success(menuService.findMenuById(menuId));
    }

    /**
     * 新增菜单
     *
     * @param menu 菜单信息
     * @return 结果
     */
    @PreAuthorize("@ss.hasPermi('system:menu:add')")
    @PostMapping
    @Log(title = "新增菜单", businessType = BusinessTypeEnum.INSERT)
    public JsonResult insertNewMenu(@Validated @RequestBody SysMenu menu) {
        if (!menuService.checkMenuNameUnique(menu)) {
            return JsonResult.error("新增菜单失败，菜单名称已经存在");
        }
        if(SystemConstants.YES_FRAME.equals(menu.getIsFrame())
                && !StringUtils.startsWithAny(menu.getPath(), Constants.HTTP, Constants.HTTPS)) {
            return JsonResult.error("新增菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        }
        int i = menuService.insertMenu(menu);

        return i > 0 ? JsonResult.success(i) : JsonResult.error("新增失败");
    }

    /**
     * 修改菜单
     *
     * @param menu 菜单
     * @return 结果
     */
    @PreAuthorize("@ss.hasPermi('system:menu:edit')")
    @PutMapping
    @Log(title = "修改菜单", businessType = BusinessTypeEnum.UPDATE)
    public JsonResult updateMenu(@Validated @RequestBody SysMenu menu) {
        if (!menuService.checkMenuNameUnique(menu)) {
            return JsonResult.error("修改菜单失败，菜单名称已经存在");
        }
        if(SystemConstants.YES_FRAME.equals(menu.getIsFrame())
                && !StringUtils.startsWithAny(menu.getPath(), Constants.HTTP, Constants.HTTPS)) {
            return JsonResult.error("修改菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        }
        int i = menuService.updateMenu(menu);

        return i > 0 ? JsonResult.success(i) : JsonResult.error("修改失败");
    }

    /**
     * 删除菜单
     *
     * @param menuId 菜单ID
     * @return 结果
     */
    @PreAuthorize("@ss.hasPermi('system:menu:delete')")
    @DeleteMapping("/{menuId}")
    @Log(title = "删除菜单", businessType = BusinessTypeEnum.DELETE)
    public JsonResult deleteMenu(@PathVariable Long menuId) {
        if(menuService.hasChildByMenuId(menuId)) {
            return JsonResult.error("存在子菜单，不允许删除");
        }
        if(menuService.checkMenuExistRole(menuId)) {
            return JsonResult.error("菜单已被分配角色，不允许删除");
        }
        int i = menuService.deleteMenuById(menuId);
        return i > 0 ? JsonResult.success(i) : JsonResult.error("删除菜单失败");
    }
    /**
     * 获取菜单的树形列表
     *
     * @return 菜单树
     */
    @GetMapping("/menuTree")
    public JsonResult menuTree(SysMenu menu) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long userId = loginUser.getUser().getUserId();
        List<SysMenu> menus = menuService.findMenuList(menu, userId);
        return JsonResult.success(menuService.buildMenuTreeSelect(menus));

    }

    /**
     * 根据角色id 查找角色对应的菜单信息
     *
     * @param roleId 角色ID
     * @return 菜单列表
     */
    @GetMapping("/roleMenuTree/{roleId}")
    public JsonResult roleMenuTree(@PathVariable Long roleId) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        List<SysMenu> menus = menuService.findMenuList(loginUser.getUser().getUserId());
        Map<String, Object> map = new HashMap<>(2);
        map.put("checkedKeys", menuService.findMenuListByRoleId(roleId));
        map.put("menus", menuService.buildMenuTreeSelect(menus));
        return JsonResult.success(map);
    }


}
